<?php
include_once __DIR__.'/config/env_config.php';
include_once __DIR__.'/vendor/autoload.php';
include_once __DIR__.'/lib/Helper.php';
include_once __DIR__.'/lib/Weixin.php';

$ticketsDataFile = __DIR__."/data/tickets.json";
$saTicketIdsFile = __DIR__."/data/special_attention_ticket_ids.json";
$saTicketDataFile = __DIR__."/data/special_attention_tickets.json";

echo date('Y-m-d H:i:s');
echo "\n";

// recent ticket
try {
    $recentTickets = Helper::recentTickets();
    file_put_contents($ticketsDataFile, json_encode($recentTickets));
    echo "recent tickets"."\t".count($recentTickets);

    $mailSendResult = Helper::emailTickets(array_filter($recentTickets, function($ticket) {
        $date = explode('-', $ticket['open_date']);
        $date = $date[2].'-'.$date[0].'-'.$date[1];
        return in_array(Helper::ticketLevel($ticket), array('danger', 'warn')) 
            && strtotime($date) > time() - 2 * 30 * 24 * 60 * 60;
    }));
    if ($mailSendResult > 0) {
        $weixin = new Weixin();
        $weixinSendResult = $weixin->sendText('主人，有一些Ticket需要处理。http://www.wishwi.tk');
        if (!$weixinSendResult) {
            echo "\nweixin send failed. response:\n";
            print_r($weixin->response);
        }
    } else {
        echo "\nmail send failed";
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}
echo "\n";

// special attention ticket
try {
    $saTicketIds = json_decode(file_get_contents($saTicketIdsFile), true);
    $saTickets = Helper::specifiedTickets($saTicketIds);
    file_put_contents($saTicketDataFile, json_encode($saTickets));
    echo "special attention tickets"."\t".count($saTickets);
} catch (\Exception $e) {
    echo $e->getMessage();    
}
echo "\n";

echo "\n";

